package com.j180.spring_jwt_demo.Interceptor;

import com.auth0.jwt.JWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j180.spring_jwt_demo.bean.ResultBean;
import com.j180.spring_jwt_demo.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("请入拦截器");

        ResultBean resultBean = new ResultBean();

        String token = request.getHeader("Authorization");

        if(token!=null){
            //验证啊
            try {
                JWTUtil.verifyToken(token);

                resultBean.setCode(0);
                resultBean.setMsg("已登录");
                return true;
            }catch (Exception e) {
                e.printStackTrace();
                resultBean.setCode(1);
                resultBean.setMsg("授权异常");
            }

        }else{
            resultBean.setCode(1);
            resultBean.setMsg("你未登录，请先登录");
        }

        ObjectMapper objectMapper = new ObjectMapper();

        String json = objectMapper.writeValueAsString(resultBean);

        response.getWriter().print(json);

        return false;
    }
}
